import { useStorage } from '@vueuse/core'
// 获取当前用户
export function getUserInfo() {
  const user = useStorage('user', '')
  if (user.value)
    return JSON.parse(user.value)
}

// 获取当前聊天对象
export function getTalkDetail() {
  const talk = useStorage('talk_detail', '')
  if (talk.value)
    return JSON.parse(talk.value)
}

// 发送消息时 补充 talkId to from 字段
export function appendSendParams() {
  const userId = getUserInfo().id
  const talkDetail = getTalkDetail()
  const params = {
    from: userId, // 发送人Id 可以从getUserInfo中获取
    talkId: talkDetail.id, // 聊天id 可以从getTalkDetail中获取
    to: talkDetail.userId, // 接收人Id 可以从getTalkDetail中获取
  }

  return params
}

// 判断当前聊天内容是否是商品
export function whetherShareGoods(text: any) {
  if (typeof text !== 'string' || !text.trim().startsWith('{') || !text.trim().endsWith('}'))
    return false

  try {
    const parsedText = JSON.parse(text)
    if (parsedText?.id && parsedText?.goodsId)
      return parsedText
  }
  catch (e) {
    // 如果JSON解析失败，返回false
    return false
  }
  return false
}

// 判断当前聊天内容是否是商品
export function whetherShareOrder(text: any): any {
  if (typeof text !== 'string' || !text.trim().startsWith('{') || !text.endsWith('}'))
    return false

  try {
    const parsedText = JSON.parse(text)
    if (parsedText?.sn && parsedText?.tradeSn)
      return parsedText

    return false
  }
  catch (e) {
    // 如果JSON解析失败，返回false
    return false
  }
}
